package com.bootdo.collection.utils;


import com.bootdo.collection.domain.PushStationDO;
import com.bootdo.collection.service.PushStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Component
public class ChangeImageSizeUtil {
    @Autowired
    private PushStationService pushStationService;
    /**裁剪图片的方法
     * @param pushStaionIds 推送地址
     * @param bytes 图片字节
     * @return
     */
    public Map<Integer,InputStream> getChangeImageInput(int[] pushStaionIds,byte[] bytes) throws Exception {
        InputStream input = null;
        BufferedImage bufferedImage;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Map<Integer,InputStream>  picStreamMap = new HashMap<>();
        PushStationDO pushStationDO;
        try {
                input = new ByteArrayInputStream(bytes);
                bufferedImage = ImageIO.read(input);
            for(int id:pushStaionIds) {
                double width = bufferedImage.getWidth();
                double height = bufferedImage.getHeight();
                pushStationDO = pushStationService.get(id);
                if(pushStationDO == null){
                    throw new Exception("不存在推送站点");
                }
                if(width > 200 && height > 200){
                   double scale = width/height;
                   width = width + pushStationDO.getPictureSize();
                   height = width/scale;
                }
                BufferedImage to = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
                to.getGraphics().drawImage(bufferedImage.getScaledInstance((int)width, (int)height, Image.SCALE_SMOOTH), 0, 0, null);
                //转字节流
                input = new ByteArrayInputStream(bufferedImageTobytes(to, 0.95f));
                picStreamMap.put(pushStationDO.getPushStationId(),input);
                input.reset();
            }
           return picStreamMap;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(input !=null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     *
     * 自己设置压缩质量来把图片压缩成byte[]
     *
     * @param image
     *            压缩源图片
     * @param quality
     *            压缩质量，在0-1之间，
     * @return 返回的字节数组
     */
    private static byte[] bufferedImageTobytes(BufferedImage image, float quality) {
        // 如果图片空，返回空
        if (image == null) {
            return null;
        }
        // 得到指定Format图片的writer
        Iterator<ImageWriter> iter = ImageIO
                .getImageWritersByFormatName("jpg");// 得到迭代器
        ImageWriter writer = (ImageWriter) iter.next(); // 得到writer

        // 得到指定writer的输出参数设置(ImageWriteParam )
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩
        iwp.setCompressionQuality(quality); // 设置压缩质量参数
        iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        ColorModel colorModel = ColorModel.getRGBdefault();
        // 指定压缩时使用的色彩模式
        iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,
                colorModel.createCompatibleSampleModel(16, 16)));

        // 开始打包图片，写入byte[]
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流
        IIOImage iIamge = new IIOImage(image, null, null);
        try {
            // 此处因为ImageWriter中用来接收write信息的output要求必须是ImageOutput
            // 通过ImageIo中的静态方法，得到byteArrayOutputStream的ImageOutput
            writer.setOutput(ImageIO
                    .createImageOutputStream(byteArrayOutputStream));
            writer.write(null, iIamge, iwp);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }
}
